package com.kpmg.datalake.accountcheck.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.plugins.Page;
import com.github.pagehelper.PageInfo;
import com.kpmg.datalake.accountcheck.service.AccountCheckService;
import com.kpmg.datalake.accountcheck.vo.AccountCheckChangeRowVO;
import com.kpmg.datalake.accountcheck.vo.AccountCheckCstVO;
import com.kpmg.datalake.accountcheck.vo.AccountCondition;
import com.kpmg.datalake.accountcheck.vo.AccountConfMappingVO;
import com.kpmg.datalake.accountcheck.vo.AccountCourseInfoByTypeVO;
import com.kpmg.datalake.accountcheck.vo.AccountCourseInfoVO;
import com.kpmg.datalake.accountcheck.vo.AccountQueryVO;
import com.kpmg.datalake.accountcheck.vo.AccountRowDeleteVO;
import com.kpmg.datalake.accountcheck.vo.AccountSubCondition;
import com.kpmg.datalake.common.enums.ReportTypeEnum;
import com.kpmg.datalake.common.model.DimInfo;
import com.kpmg.datalake.common.model.ReportDate;
import com.kpmg.datalake.common.privilege.ValidateDataAuth;
import com.kpmg.datalake.common.service.BaseInfoService;
import com.kpmg.datalake.common.vo.BasePageQueryVO;
import com.kpmg.datalake.common.vo.CorpQueryVO;
import com.kpmg.datalake.common.vo.GeneralHeaderVO;
import com.kpmg.datalake.common.vo.ServerResponse;
import com.kpmg.datalake.operatelog.annotation.OptLog;
import com.kpmg.datalake.operatelog.enums.LogTypeEnum;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

/**
 * @author Echo
 * @create 2018-05-17
 * @desc 内部对账相关服务
 */
@RestController
@RequestMapping("/account_check")
public class AccountCheckController {

    @Autowired
    private BaseInfoService baseInfoService;

    private static final Logger logger = LoggerFactory.getLogger(AccountCheckController.class);
    private static final String SPLITER = " ";
    @Autowired
    private AccountCheckService accountCheckService;

    @GetMapping("")
    public ModelAndView accountCheckIndex() {
        ModelAndView view = new ModelAndView();
        view.setViewName("account_check");
        return view;
    }

    /**
     * 初始化客户名称
     *
     * @param corpQueryVO
     * @return
     */
    @RequestMapping(value = "/initCorp")
    public ServerResponse initCorp(@RequestBody CorpQueryVO corpQueryVO) {

        try {
            PageInfo pageInfo = baseInfoService.initCorp(corpQueryVO.getPageNum(), corpQueryVO.getPageSize(), corpQueryVO.getProjectId(), corpQueryVO.getQueryParam());

            return ServerResponse.createBySuccess("初始化客户名称成功！", pageInfo);
        } catch (Exception e) {
            logger.error("初始化客户名称时异常:" + e.getMessage(), e);
            return ServerResponse.createByError();

        }

    }

    /**
     * 获取会计年月
     *
     * @param projectId
     * @return
     */
    @GetMapping("/initReportDate")
    public ServerResponse getAccYearMonth(@RequestParam(value = "projectId") String projectId) {

        
        List<ReportDate> reportDates = baseInfoService.initDate(projectId);
        if (!reportDates.isEmpty()) {

            return ServerResponse.createBySuccess("初始化报告日期范围成功！", new ArrayList<>(reportDates));
        } else {
            return ServerResponse.createByError();
        }

    }



    @PostMapping("/getAccountCheckList")
    @OptLog(logType = LogTypeEnum.OPERATION, module = "accountCheck", description = "查询内部对账数据")
    @ValidateDataAuth(key = "#accountQueryVO.getProjectId()")
    public ServerResponse<JSONObject> getAccountCheckList(@RequestBody AccountQueryVO accountQueryVO) {

        return accountCheckService.getChkAccountData(accountQueryVO.getProjectId(), accountQueryVO, accountQueryVO.getBatchNum(), accountQueryVO.getOffsetType());
    }

    /**
     * 导出报表信息
     *
     * @param accountQueryVO
     * @param request
     * @param response
     */
    @RequestMapping(value = "/exportReport", method = RequestMethod.POST)
    @OptLog(logType = LogTypeEnum.OPERATION, module = "accountCheck", description = "导出内部对账数据")
    public void exportReport(@RequestBody AccountQueryVO accountQueryVO, HttpServletRequest request, HttpServletResponse response) {

        try {

            String corpDetail = accountQueryVO.getCorpNm();
            logger.info("导出 {}", corpDetail);
            if (corpDetail.split(SPLITER).length > 1) {
                accountQueryVO.setCorpCd(corpDetail.split(SPLITER)[0]);
                accountQueryVO.setCorpNm(corpDetail.split(SPLITER)[1]);
            }
            // 导出报表记录
            accountCheckService.exportAccountReport(accountQueryVO.getProjectId(), accountQueryVO.getFileName(), accountQueryVO, request, response);

            logger.info("{}成功！", "导出报表信息");
        } catch (Exception e) {
            logger.error("导出报表信息，异常:{}", e.getMessage());
        }
    }

    /**
     * 获取科目信息
     * @param courseInfoVO
     * @return
     */
    @PostMapping("/getCourseInfo")
    public ServerResponse<PageInfo> getCourseInfo(@RequestBody AccountCourseInfoVO  courseInfoVO) {
        return accountCheckService.getCourseList(courseInfoVO.getPageNum(), courseInfoVO.getPageSize(), courseInfoVO.getProjectId(), courseInfoVO.getCorpCode(), courseInfoVO.getQueryParam());
    }

    /**
     * 手工添加抵消分录
     * @param accountRow
     * @return
     */
    @PostMapping("/addAccountRow")
    @OptLog(logType = LogTypeEnum.OPERATION, module = "accountCheck", description = "添加抵消")
    public ServerResponse<JSONObject> addAccountRow(@RequestBody AccountCondition accountRow) {
        return accountCheckService.addManualRow(accountRow, accountRow.getProjectId());
    }

    /**
     * 删除手工添加的分录
     * @param accountRowDeleteVO
     * @return
     */
    @PostMapping("/deleteAccountRow")
    public ServerResponse<JSONObject> deleteAccountRow(@RequestBody AccountRowDeleteVO accountRowDeleteVO) {
    	return accountCheckService.deleteManualRow(accountRowDeleteVO, accountRowDeleteVO.getProjectId());
    }
    
    @PostMapping("/getCstMapping")
    @OptLog(logType = LogTypeEnum.OPERATION, module = "accountCheck", description = "查询交易对手mapping")
    public ServerResponse getCstMapping(@RequestBody AccountConfMappingVO accountMapping) {
    	int page=accountMapping.getPageNum();
    	int size=accountMapping.getPageSize();
    	String projectId=accountMapping.getProjectId();
    	String param=accountMapping.getQueryParam();
    	return accountCheckService.getCstMapping(projectId, param, page, size);
    }
    
    @GetMapping("/getChildCorp")
    public ServerResponse getChildCorp(AccountConfMappingVO accountMapping) {
      JSONObject result = new JSONObject();
      try {
    	  int page=accountMapping.getPageNum();
      	  int size=accountMapping.getPageSize();
      	  String projectId=accountMapping.getProjectId();
      	  String param=accountMapping.getQueryParam();
          PageInfo<DimInfo> pageInfo = baseInfoService.getLastLevelCorp(page, size, projectId, param);
          // 是否存在下一页
          result.put("hasNextPage", pageInfo.isHasNextPage());
          result.put("list", pageInfo.getList());
          return ServerResponse.createBySuccess("初始化子节点客户名称成功！", result);
      } catch (Exception e) {
          logger.error("初始化客户名称时异常:" + e.getMessage(), e);
          return ServerResponse.createByError();

      }
    }
    
    /**
     * 更新交易对手的标准名称
     * @param cstMapping
     * @return
     */
    @PostMapping(value = "/updateCstMapping")
    @OptLog(logType = LogTypeEnum.OPERATION, module = "accountCheck", description = "修改交易对手mapping")
    public ServerResponse updateCstMapping(@RequestBody AccountCheckCstVO cstMapping) {
    	return accountCheckService.updateCstMapping(cstMapping.getProjectId(),cstMapping.getCode(),cstMapping.getValue(),cstMapping.getCorpCd(),cstMapping.getCorpNm());
    }
    @GetMapping("/counterparty_conf")
    public ModelAndView accountCheckConfIndex() {
        ModelAndView view = new ModelAndView();
        view.setViewName("counterparty_conf");
        return view;
    }
    
    @GetMapping("/account_sub_conf")
    public ModelAndView accountCheckConfSub() {
        ModelAndView view = new ModelAndView();
        view.setViewName("account_sub_conf");
        return view;
    }
    
    //获取科目匹配查询
    @PostMapping("/getSubMatchMapper")
    @OptLog(logType = LogTypeEnum.OPERATION, module = "accountCheck", description = "查询科目匹配")
    public ServerResponse getSubMatchMapping(@RequestBody AccountConfMappingVO accountMapping) {
    	return accountCheckService.getSubMatchAndDetailMapping(accountMapping.getProjectId(), accountMapping.getQueryParam(),accountMapping.getPageNum(), accountMapping.getPageSize());

    }
    
    /**
     * 根据类型获取科目信息
     *
     * @return
     */
    @PostMapping("/getCourseInfoByType")
    public ServerResponse getCourseInfoByType(@RequestBody AccountCourseInfoByTypeVO  courseInfoVO) {
    	return accountCheckService.getCourseByType(courseInfoVO.getPageNum(), courseInfoVO.getPageSize(), courseInfoVO.getProjectId(),courseInfoVO.getTypes(),courseInfoVO.getCode(),courseInfoVO.getValue(), courseInfoVO.getQueryParam());
    }
   
    @PostMapping("/addSubRule")
    @OptLog(logType = LogTypeEnum.OPERATION, module = "accountcheck", description = "新增科目匹配规则")
    public ServerResponse addSubRule(@RequestBody AccountSubCondition  accountSubCondition) {
        return accountCheckService.addRuleRow(accountSubCondition, accountSubCondition.getProjectId());
    }
    
    @PostMapping("/deleteSubRule")
    @OptLog(logType = LogTypeEnum.OPERATION, module = "accountcheck", description = "删除科目匹配规则")
    public ServerResponse deleteSubRule(@RequestBody AccountConfMappingVO accountMapping) {
        return accountCheckService.deleteRuleRow(accountMapping.getQueryParam(), accountMapping.getProjectId());
    }
    
    @PostMapping("/updateRuleAllRow")
    @OptLog(logType = LogTypeEnum.OPERATION, module = "accountcheck", description = "修改科目匹配规则")
    public ServerResponse updateRuleAllRow(@RequestBody AccountSubCondition  accountSubCondition) {
        return accountCheckService.updateRuleAllRow(accountSubCondition,accountSubCondition.getProjectId());
    }
    
    @PostMapping("/moveRuleRowPriority")
    @OptLog(logType = LogTypeEnum.OPERATION, module = "accountcheck", description = "调换科目匹配规则顺序")
    public ServerResponse moveUpdateRulePriority(@RequestBody AccountCheckChangeRowVO  accountSubCondition) {
        return accountCheckService.moveAccountSubHeader(accountSubCondition,accountSubCondition.getProjectId());
    }

    @PostMapping("/getJournalDetailTableHeader")
    public ServerResponse<ArrayList<GeneralHeaderVO>> getJournalDetailTableHeader(
        @RequestBody BasePageQueryVO baseQueryVO) {
        logger.info("getJournalDetailTableHeader with ProjectId {}", baseQueryVO.getProjectId());
        return accountCheckService
            .getJournalDetailTableHeader(baseQueryVO.getProjectId(), ReportTypeEnum.JOURNAL_IR.getCode());
    }

    @PostMapping("/getAccountCheckJournalDetail")
    public ServerResponse<Page<Map<String, Object>>> getAccountCheckJournalDetail(
        @RequestBody AccountConfMappingVO accountConfMappingVO) {
        return accountCheckService.getAccountCheckJournalDetail(accountConfMappingVO.getPageNum(),
            accountConfMappingVO.getPageSize(), accountConfMappingVO.getProjectId(),
            ReportTypeEnum.JOURNAL_IR.getCode(), accountConfMappingVO.getQueryParam());
    }
}
